package com.cskaoyan.wx.service;

import com.cskaoyan.bean.reverseengineering.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.wx.bean.bo.cartbo.CartAddBO;
import com.cskaoyan.wx.bean.bo.cartbo.CartCheckedBO;
import com.cskaoyan.wx.bean.bo.cartbo.CartDeleteBO;
import com.cskaoyan.wx.bean.bo.cartbo.CartUpdateBO;
import com.cskaoyan.wx.bean.vo.cartvo.CartCheckOutVO;
import com.cskaoyan.wx.bean.vo.cartvo.CartIndexVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * 类说明
 *
 * @author zhangfuqiang
 * @date 2022/5/8
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    CartService cartService;

    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketGoodsMapper marketgoodsMapper;

    @Autowired
    MarketGoodsProductMapper marketGoodsProductMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Autowired
    MarketGrouponRulesMapper marketGrouponRulesMapper;

    @Autowired
    MarketUserMapper marketUserMapper;

    @Autowired
    MarketSystemMapper marketSystemMapper;


    //获得用户id
    @Override
    public Integer getIdByUsername() {
        Subject subject = SecurityUtils.getSubject();
        String username = (String) subject.getPrincipals().getPrimaryPrincipal();
        MarketUser marketUser = marketUserMapper.queryByUsername(username);
        Integer id = marketUser.getId();
        return id;
    }

    @Override
    public CartIndexVO index() {
        //获取用户id
        Integer idByUsername = cartService.getIdByUsername();
        //给订单列表赋值,根据userid拿对应的数据
        CartIndexVO cartIndexVO = new CartIndexVO();
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria().andUserIdEqualTo(idByUsername);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);

        //倒序输出
        LinkedList<MarketCart> temp = new LinkedList<>();
        for (int i = 0; i < marketCarts.size(); i++) {
            temp.addFirst(marketCarts.get(i));
        }
        marketCarts = temp;

        //若删除状态为true则从链表中去除
        Iterator<MarketCart> iterator = marketCarts.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().getDeleted()) {
                iterator.remove();
            }
        }

        cartIndexVO.setCartList(marketCarts);

        //统计确定要付款的订单
        int checkedGoodsCount = 0;
        double checkedGoodsAmount = 0;
        int goodsCount = 0;
        double goodsAmount = 0;
        for (MarketCart marketCart : marketCarts) {
            goodsCount++;
            goodsAmount += marketCart.getPrice().doubleValue() * marketCart.getNumber();
            if (marketCart.getChecked() == true) {
                checkedGoodsCount++;
                checkedGoodsAmount += marketCart.getPrice().doubleValue() * marketCart.getNumber();
            }
        }
        CartIndexVO.CartTotalEntity cartTotal = cartIndexVO.getCartTotal();
        cartTotal.setGoodsAmount(goodsAmount);
        cartTotal.setGoodsCount(goodsCount);
        cartTotal.setCheckedGoodsAmount(checkedGoodsAmount);
        cartTotal.setCheckedGoodsCount(checkedGoodsCount);

        return cartIndexVO;
    }

    @Override
    public CartIndexVO checked(CartCheckedBO cartCheckedBO) {

        //根据productIds修改checked值
        List<Integer> productIds = cartCheckedBO.getProductIds();
        Integer isChecked = cartCheckedBO.getIsChecked();
        MarketCart marketCart = new MarketCart();
        if (isChecked == 1) {
            marketCart.setChecked(true);
        } else if (isChecked == 0) {
            marketCart.setChecked(false);
        }

        for (Integer productId : productIds) {
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andProductIdEqualTo(productId);
            marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);
        }

        //返回购物车的值
        CartIndexVO cartIndexVO = cartService.index();

        return cartIndexVO;
    }


    @Override
    public Boolean update(CartUpdateBO cartUpdateBO) {
        Integer id = cartUpdateBO.getId();
        Integer goodsId = cartUpdateBO.getGoodsId();
        Integer number = cartUpdateBO.getNumber();
        Integer productId = cartUpdateBO.getProductId();

        MarketCart marketCart = new MarketCart();
        marketCart.setGoodsId(goodsId);
        marketCart.setNumber(number);
        marketCart.setProductId(productId);

        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andIdEqualTo(id);
        marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);

        return true;
    }

    @Override
    public CartIndexVO delete(CartDeleteBO cartDeleteBO) {
        //根据productIds修改deleted值为true
        List<Integer> productIds = cartDeleteBO.getProductIds();
        MarketCart marketCart = new MarketCart();
        marketCart.setDeleted(true);

        for (Integer productId : productIds) {
            MarketCartExample marketCartExample = new MarketCartExample();
            MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
            criteria.andProductIdEqualTo(productId);
            marketCartMapper.updateByExampleSelective(marketCart, marketCartExample);
        }

        //返回购物车的值
        CartIndexVO cartIndexVO = cartService.index();

        return cartIndexVO;
    }

    @Override
    public int add(CartAddBO cartAddBO) {
        Integer goodsId = cartAddBO.getGoodsId();
        Integer number = cartAddBO.getNumber();
        Integer productId = cartAddBO.getProductId();
        Integer idByUsername = cartService.getIdByUsername();

        //根据idByUsername,goodsId和productId查询商品是否存在
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andGoodsIdEqualTo(goodsId);
        criteria.andProductIdEqualTo(productId);
        criteria.andUserIdEqualTo(idByUsername);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);


        //商品不存在则插入，存在则更新数量
        //若商品已经是删除状态，直接插入
        if (marketCarts.size() == 0) {
            MarketCart marketCart = new MarketCart();
            //从session中拿用户信息
            marketCart.setUserId(idByUsername);
            marketCart.setGoodsId(goodsId);
            marketCart.setProductId(productId);
            marketCart.setNumber(number);
            Date date = new Date();
            marketCart.setAddTime(date);
            marketCart.setUpdateTime(date);
            marketCart.setDeleted(false);
            marketCart.setChecked(true);
            //根据goodsId拿sn和name,pic_url
            MarketGoods marketGoods = marketgoodsMapper.selectByPrimaryKey(goodsId);
            marketCart.setGoodsSn(marketGoods.getGoodsSn());
            marketCart.setGoodsName(marketGoods.getName());
            marketCart.setPicUrl(marketGoods.getPicUrl());
            //根据productId拿price,speci
            MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);
            marketCart.setPrice(marketGoodsProduct.getPrice());
            marketCart.setSpecifications(marketGoodsProduct.getSpecifications());
            //插入表中
            int insert = marketCartMapper.insertSelective(marketCart);
        } else {
            MarketCart marketCart0 = marketCarts.get(0);
            Boolean deleted = marketCart0.getDeleted();
            if (deleted) {
                MarketCart marketCart = new MarketCart();
                //从session中拿用户信息
                marketCart.setUserId(idByUsername);
                marketCart.setGoodsId(goodsId);
                marketCart.setProductId(productId);
                marketCart.setNumber(number);
                Date date = new Date();
                marketCart.setAddTime(date);
                marketCart.setUpdateTime(date);
                marketCart.setDeleted(false);
                marketCart.setChecked(true);
                //根据goodsId拿sn和name,pic_url
                MarketGoods marketGoods = marketgoodsMapper.selectByPrimaryKey(goodsId);
                marketCart.setGoodsSn(marketGoods.getGoodsSn());
                marketCart.setGoodsName(marketGoods.getName());
                marketCart.setPicUrl(marketGoods.getPicUrl());
                //根据productId拿price,speci
                MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);
                marketCart.setPrice(marketGoodsProduct.getPrice());
                marketCart.setSpecifications(marketGoodsProduct.getSpecifications());
                //插入表中
                int insert = marketCartMapper.insertSelective(marketCart);
            } else {
                //商品已经存在，且处于未删除状态，增加商品数量
                marketCart0.setNumber(marketCart0.getNumber() + number);
                marketCartMapper.updateByPrimaryKeySelective(marketCart0);
            }

        }


        int goodscount = cartService.goodscount();
        return goodscount;
    }

    @Override
    public int goodscount() {

        //获取用户id
        Integer idByUsername = cartService.getIdByUsername();

        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria().andUserIdEqualTo(idByUsername);
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);

        //若删除状态为true则从链表中去除
        Iterator<MarketCart> iterator = marketCarts.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().getDeleted()) {
                iterator.remove();
            }
        }
        int count = 0;
        for (MarketCart marketCart : marketCarts) {
            count += marketCart.getNumber();
        }
        return count;
    }

    @Override
    public int fastadd(CartAddBO cartAddBO) {
        Integer goodsId = cartAddBO.getGoodsId();
        Integer number = cartAddBO.getNumber();
        Integer productId = cartAddBO.getProductId();

        MarketCart marketCart = new MarketCart();
        //从session中拿用户信息
        Integer idByUsername = cartService.getIdByUsername();
        marketCart.setUserId(idByUsername);

        marketCart.setGoodsId(goodsId);
        marketCart.setProductId(productId);
        marketCart.setNumber(number);
        Date date = new Date();
        marketCart.setAddTime(date);
        marketCart.setUpdateTime(date);
        //置入购物车中直接删除，只为了拿id
        marketCart.setDeleted(true);
        marketCart.setChecked(false);

        //根据goodsId拿sn和name,pic_url
        MarketGoods marketGoods = marketgoodsMapper.selectByPrimaryKey(goodsId);
        marketCart.setGoodsSn(marketGoods.getGoodsSn());
        marketCart.setGoodsName(marketGoods.getName());
        marketCart.setPicUrl(marketGoods.getPicUrl());

        //根据productId拿price,speci
        MarketGoodsProduct marketGoodsProduct = marketGoodsProductMapper.selectByPrimaryKey(productId);
        marketCart.setPrice(marketGoodsProduct.getPrice());
        marketCart.setSpecifications(marketGoodsProduct.getSpecifications());

        //插入表中，获取自增主键
        marketCartMapper.insertToGetKey(marketCart);
        Integer id = marketCart.getId();

        return id;
    }

    @Override
    public CartCheckOutVO checkout(Integer cartId, Integer addressId,
                                   Integer couponId, Integer userCouponId, Integer grouponRulesId) {

        int i = couponId;
        //整合用户信息
        Integer idByUsername = cartService.getIdByUsername();

        CartCheckOutVO cartCheckOutVO = new CartCheckOutVO();
        //若cartId为0，则把所有checked为true的订单返回；若不为0，就根据主键查询订单并且返回
        MarketCartExample marketCartExample = new MarketCartExample();
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        //查到用户对应的所有订单
        criteria.andUserIdEqualTo(idByUsername);
        if (cartId == 0) {
            criteria.andCheckedEqualTo(true);
        } else {
            criteria.andIdEqualTo(cartId);
        }
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);

        /*//若删除状态为true则从链表中去除
        //会造成fastadd失效
        Iterator<MarketCart> iterator = marketCarts.iterator();
        while (iterator.hasNext()) {
            if (iterator.next().getDeleted()) {
                iterator.remove();
            }
        }*/

        double goodsTotalPrice = 0;
        for (MarketCart marketCart : marketCarts) {
            goodsTotalPrice += marketCart.getPrice().doubleValue() * marketCart.getNumber();
            marketCartMapper.updateByPrimaryKeySelective(marketCart);
        }
        cartCheckOutVO.setCheckedGoodsList(marketCarts);
        cartCheckOutVO.setCartId(cartId);
        //商品合计
        cartCheckOutVO.setGoodsTotalPrice(goodsTotalPrice);


        //查询地址信息
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(addressId);
        cartCheckOutVO.setCheckedAddress(marketAddress);
        cartCheckOutVO.setAddressId(addressId);


        //查询用户的优惠券信息，先查询到用户的所有的优惠券；再根据优惠券id去查询优惠券折扣金额
        MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria2 = marketCouponUserExample.createCriteria();
        //用户的优惠券
        criteria2.andUserIdEqualTo(idByUsername);
        //处于可用状态
        criteria2.andStatusEqualTo(Short.parseShort("0"));
        //使用时间限制
        Date date = new Date();
        criteria2.andStartTimeLessThanOrEqualTo(date);
        criteria2.andEndTimeGreaterThanOrEqualTo(date);

        List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);


        //根据用户可用的优惠券id查询优惠券信息
        //若couponId为0，查询所有可用优惠券,找到面额最大的优惠券使用
        //若couponId为-1，不使用优惠券
        //若不为0，就根据主键查询优惠券
        MarketCouponExample marketCouponExample = new MarketCouponExample();
        MarketCouponExample.Criteria criteria1 = marketCouponExample.createCriteria();
        //使用金额限制
        criteria1.andMinLessThanOrEqualTo(BigDecimal.valueOf(goodsTotalPrice));
        if (couponId == 0 || couponId == -1) {
            criteria1.andDeletedEqualTo(false);
        } else {
            criteria1.andIdEqualTo(couponId);
        }
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(marketCouponExample);
        //若查到的优惠券id不在用户可用优惠券id内，就剔除
        LinkedList<Integer> validCouponId = new LinkedList<>();
        for (MarketCouponUser marketCouponUser : marketCouponUsers) {
            validCouponId.add(marketCouponUser.getCouponId());
        }

        Iterator<MarketCoupon> iterator2 = marketCoupons.iterator();
        while (iterator2.hasNext()) {
            if (!validCouponId.contains(iterator2.next().getId())) {
                iterator2.remove();
            }
        }
        int couponPrice = 0;
        if (marketCoupons.size() != 0) {
            for (MarketCoupon marketCoupon : marketCoupons) {
                int v = marketCoupon.getDiscount().intValue();
                if (couponPrice < v) {
                    couponPrice = v;
                    couponId = marketCoupon.getId();
                }
            }
        }

        //根据选中的优惠券，再回查user的优惠券id
        MarketCouponUserExample marketCouponUserExample2 = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria3 = marketCouponUserExample2.createCriteria();
        criteria3.andCouponIdEqualTo(couponId);
        List<MarketCouponUser> marketCouponUsers1 = marketCouponUserMapper.selectByExample(marketCouponUserExample2);
        if (marketCouponUsers1.size() != 0) {
            userCouponId = marketCouponUsers1.get(0).getId();
        }

        //不选择优惠券折扣为0
        if (i == -1) {
            couponPrice = 0;
            couponId = -1;
            userCouponId = -1;
        }
        cartCheckOutVO.setCouponPrice(couponPrice);

        //返回已使用的优惠券对应id
        cartCheckOutVO.setCouponId(couponId);
        cartCheckOutVO.setUserCouponId(userCouponId);

        //可用的优惠券数量
        int availableCouponLength = 0;
        for (MarketCoupon marketCoupon : marketCoupons) {
            availableCouponLength++;
        }
        cartCheckOutVO.setAvailableCouponLength(availableCouponLength);


        //查询团购规则表信息，不会用团购
        cartCheckOutVO.setGrouponRulesId(grouponRulesId);
        //MarketGrouponRules marketGrouponRules = marketGrouponRulesMapper.selectByPrimaryKey(grouponRulesId);


        //团购价暂不考虑
        cartCheckOutVO.setGrouponPrice(0);

        //计算运费
        MarketSystem marketSystem = marketSystemMapper.selectByPrimaryKey(6);
        MarketSystem marketSyste2 = marketSystemMapper.selectByPrimaryKey(8);
        if (goodsTotalPrice < Double.parseDouble(marketSystem.getKeyValue())) {
            cartCheckOutVO.setFreightPrice(Integer.parseInt(marketSyste2.getKeyValue()));
        } else {
            cartCheckOutVO.setFreightPrice(0);
        }

        //认为订单总价等于实付
        double actualPrice = goodsTotalPrice - couponPrice + cartCheckOutVO.getFreightPrice();
        cartCheckOutVO.setActualPrice(actualPrice);
        cartCheckOutVO.setOrderTotalPrice(actualPrice);

        return cartCheckOutVO;
    }
}
